package com.young.shop.api.service.impl;

import com.young.shop.api.dao.CouponMapper;
import com.young.shop.api.exceptions.BaseException;
import com.young.shop.api.service.CouponService;
import com.young.shop.pojo.entity.Coupon;
import com.young.shop.pojo.qo.CouponQO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;


@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    private CouponMapper couponMapper;

    @Override
    public List<Coupon> getCoupon() {
        List<Coupon> coupons = couponMapper.selectCoupon();
        return coupons;
    }

    @Override
    public int receiveCoupon(int userId, String code) {

        //根据id查询用户是领取过几次这张优惠券，并判断是否能再次领取
        CouponQO couponQO = couponMapper.selectOneCoupon(userId, code);
        if (couponQO != null) {
            int couponNumber = couponQO.getCouponNumber();
            int perLimit = couponQO.getPerLimit();
            if (couponNumber == perLimit) {
                throw new BaseException("已经到达领取上限");
            }else {
                //没有到达上限则新增优惠券
                couponNumber += 1;
                int i = couponMapper.insertUserCoupon(userId, couponNumber, code);
                return i;
            }
        }
        int i = couponMapper.insertUserCoupon(userId, 1, code);
        return i;
    }

    @Override
    public List<CouponQO> getPersonCoupon(int userId) {
        return couponMapper.selectPersonCoupon(userId);
    }

    @Override
    public List<CouponQO> getPayCoupon(BigDecimal orderPrice, Integer userId) {
        return couponMapper.selectPayCoupon(userId,orderPrice);
    }
}
